<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {handleError, success, warning} from '@/utils/message'
import {MESSAGES, PICTURE} from '@/constants/messages'
import {CheckOutlined, CloseOutlined, EyeOutlined} from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import {pictureApi} from '@/api'
import type {PictureVO} from '@/types/vo/picture'
import {getReviewStatusColor, getReviewStatusText} from '@/constants/picture'

const loading = ref(false)
const reviewing = ref(false)
const detailModalVisible = ref(false)
const rejectModalVisible = ref(false)
const reviewStatus = ref<number | undefined>(0) // 默认显示待审核

const pictureList = ref<PictureVO[]>([])
const selectedPicture = ref<PictureVO | null>(null)
const rejectReason = ref('')

const pagination = reactive({
  current: 1,
  size: 12,
  total: 0
})

// 加载图片列表
const loadPictures = async () => {
  loading.value = true
  try {
    const result = await pictureApi.list({
      current: pagination.current,
      size: pagination.size,
      reviewStatus: reviewStatus.value
    })
    pictureList.value = result.records
    pagination.total = result.total
  } catch (error: any) {
    handleError(error, PICTURE.LOAD_FAILED)
  } finally {
    loading.value = false
  }
}

// 筛选
const handleFilter = () => {
  pagination.current = 1
  loadPictures()
}

// 分页变化
const handlePageChange = () => {
  loadPictures()
}

// 查看图片
const viewPicture = (picture: PictureVO) => {
  selectedPicture.value = picture
  detailModalVisible.value = true
}

// 审核图片
const reviewPicture = async (picture: PictureVO, status: number) => {
  reviewing.value = true
  try {
    await pictureApi.review(picture.id!, {
      reviewStatus: status,
      reviewMessage: status === 1 ? '审核通过' : ''
    })
    success(status === 1 ? '已通过' : '已拒绝')
    loadPictures()
  } catch (error: any) {
    handleError(error, MESSAGES.FAILED)
  } finally {
    reviewing.value = false
  }
}

// 显示拒绝对话框
const showRejectModal = (picture: PictureVO) => {
  selectedPicture.value = picture
  rejectReason.value = ''
  rejectModalVisible.value = true
}

// 处理拒绝
const handleReject = async () => {
  if (!rejectReason.value.trim()) {
    warning('请输入拒绝理由')
    return
  }

  if (!selectedPicture.value) return

  reviewing.value = true
  try {
    await pictureApi.reviewPicture(selectedPicture.value.id!, {
      reviewStatus: 2,
      reviewMessage: rejectReason.value
    })
    success('已拒绝')
    rejectModalVisible.value = false
    loadPictures()
  } catch (error: any) {
    handleError(error, MESSAGES.FAILED)
  } finally {
    reviewing.value = false
  }
}

// 格式化日期
const formatDate = (date?: string) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : ''
}

onMounted(() => {
  loadPictures()
})
</script>

<template>
  <div class="picture-management-container">
    <a-card title="图片审核">
      <!-- 筛选 -->
      <div class="filter-section">
        <a-radio-group v-model:value="reviewStatus" button-style="solid" @change="handleFilter">
          <a-radio-button :value="undefined">全部</a-radio-button>
          <a-radio-button :value="0">待审核</a-radio-button>
          <a-radio-button :value="1">已通过</a-radio-button>
          <a-radio-button :value="2">已拒绝</a-radio-button>
        </a-radio-group>
      </div>

      <!-- 图片列表 -->
      <a-spin :spinning="loading">
        <a-list
            :data-source="pictureList"
            :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 4, xxl: 5 }"
            style="margin-top: 16px"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-card hoverable>
                <template #cover>
                  <div class="picture-cover">
                    <img :alt="item.pictureName" :src="item.thumbnailUrl || item.fileUrl"/>
                    <div class="review-status-badge">
                      <a-tag :color="getReviewStatusColor(item.reviewStatus)">
                        {{ getReviewStatusText(item.reviewStatus) }}
                      </a-tag>
                    </div>
                  </div>
                </template>
                <a-card-meta
                    :description="`上传者: ${item.user?.userName || '匿名'}`"
                    :title="item.pictureName"
                />
                <template #actions>
                  <a-tooltip title="查看">
                    <EyeOutlined @click="viewPicture(item)"/>
                  </a-tooltip>
                  <a-tooltip v-if="item.reviewStatus !== 1" title="通过">
                    <CheckOutlined @click="reviewPicture(item, 1)"/>
                  </a-tooltip>
                  <a-tooltip v-if="item.reviewStatus !== 2" title="拒绝">
                    <CloseOutlined @click="showRejectModal(item)"/>
                  </a-tooltip>
                </template>
              </a-card>
            </a-list-item>
          </template>
        </a-list>

        <!-- 分页 -->
        <div v-if="pagination.total > 0" class="pagination">
          <a-pagination
              v-model:current="pagination.current"
              v-model:page-size="pagination.size"
              :show-total="(total: number) => `共 ${total} 张图片`"
              :total="pagination.total"
              show-size-changer
              @change="handlePageChange"
          />
        </div>
      </a-spin>
    </a-card>

    <!-- 图片详情对话框 -->
    <a-modal
        v-model:open="detailModalVisible"
        :footer="null"
        title="图片详情"
        width="800px"
    >
      <div v-if="selectedPicture">
        <div class="detail-image">
          <img :alt="selectedPicture.pictureName" :src="selectedPicture.fileUrl"/>
        </div>
        <a-descriptions :column="2" style="margin-top: 16px">
          <a-descriptions-item :span="2" label="图片名称">
            {{ selectedPicture.pictureName }}
          </a-descriptions-item>
          <a-descriptions-item :span="2" label="简介">
            {{ selectedPicture.introduction || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="分类">
            {{ selectedPicture.category || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="标签">
            <a-space v-if="selectedPicture.tags && selectedPicture.tags.length > 0" wrap>
              <a-tag v-for="tag in selectedPicture.tags" :key="tag">{{ tag }}</a-tag>
            </a-space>
            <span v-else>无</span>
          </a-descriptions-item>
          <a-descriptions-item label="上传者">
            {{ selectedPicture.user?.userName || '匿名' }}
          </a-descriptions-item>
          <a-descriptions-item label="上传时间">
            {{ formatDate(selectedPicture.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="审核状态">
            <a-tag :color="getReviewStatusColor(selectedPicture.reviewStatus)">
              {{ getReviewStatusText(selectedPicture.reviewStatus) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedPicture.reviewMessage" label="审核信息">
            {{ selectedPicture.reviewMessage }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 拒绝理由对话框 -->
    <a-modal
        v-model:open="rejectModalVisible"
        :confirm-loading="reviewing"
        title="拒绝原因"
        @ok="handleReject"
    >
      <a-form layout="vertical">
        <a-form-item label="拒绝理由" required>
          <a-textarea
              v-model:value="rejectReason"
              :maxlength="200"
              :rows="4"
              placeholder="请输入拒绝原因"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="scss" scoped>
.picture-management-container {
  // 容器样式由 AdminLayout 管理
}

.filter-section {
  margin-bottom: 16px;
}

.picture-cover {
  position: relative;
  height: 200px;
  overflow: hidden;
  background: #f5f5f5;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .review-status-badge {
    position: absolute;
    top: 8px;
    right: 8px;
  }
}

.detail-image {
  text-align: center;
  max-height: 400px;
  overflow: hidden;

  img {
    max-width: 100%;
    max-height: 400px;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>